import uvicorn
from fastapi import FastAPI,HTTPException,status
from controller import Controller
import os
import json
import paramiko
# 初始化 FastAPI 应用
app = FastAPI()

# 初始化 ServerAPI 实例
controller = Controller()

@app.on_event("startup")
async def startup_event():
    controller.start()

@app.on_event("shutdown")
async def shutdown_event():
    controller.stop()



@app.get("/log")
def get_panel_log():
    """获取面板日志"""
    try:
        with open(os.path.join(os.path.dirname(__file__),'db','panel_log.json')) as f:
            return json.load(f).get("log")
    except (FileNotFoundError, json.JSONDecodeError):
        return {}

@app.get("/server-list")
def get_server_list():
    """获取服务器列表"""
    return controller.list_clients()

@app.get("/token")
def login():
    """获取服务器列表"""
    return controller.list_clients()

@app.post("/users")
def register():
    """获取服务器列表"""
    return controller.list_clients()




@app.post("/command/{client_id}")
async def send_command(client_id: str, command: str, args: dict = None):
    """向指定客户端发送命令"""
    
    result = await controller.send_command(client_id, command, args)
    if result:
        return {"status":"success", "data":result}
    else:
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST)
    




@app.post("/broadcast_command")
async def broadcast_command(command: str, args: dict = None):
    """向所有客户端广播命令"""

    result = await controller.broadcast_command(command, args)
    if result:
        
        return result
    else:
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST)
    
    

# @app.post("/stop_server")
# def stop_server():
#     """停止服务器"""
#     controller.stop()
#     return {"message": "API服务器已停止"}


@app.post("/terminal")
async def execute_command(host: str, username: str, password: str, command: str, port: int=22):
    try:
        # 创建 SSH 对象
        ssh = paramiko.SSHClient()
        # 允许连接不在 know_hosts 文件中的主机
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        # 连接服务器
        ssh.connect(hostname=host, port=port, username=username, password=password)
        # 执行命令
        stdin, stdout, stderr = ssh.exec_command(command)
        # 获取命令结果
        result = stdout.read().decode()
        # 获取错误信息
        error = stderr.read().decode()
        # 关闭连接
        ssh.close()
        if error:
            return {"status": "error", "message": error}
        return {"status": "success", "result": result}
    except Exception as e:
        return {"status": "error", "message": str(e)}
    



if __name__ == "__main__":
    try:
        uvicorn.run(app, host="0.0.0.0", port=8000)
    except KeyboardInterrupt:
        pass
